package com.mrx.commons.trace;

import com.mrx.commons.logback.config.XLogCollectorProperties;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Nullable;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @author Mr.X
 * @since 2023-11-10 16:01
 **/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceFilter extends OncePerRequestFilter {

    private XLogCollectorProperties properties;

    @Autowired(required = false)
    public void setProperties(XLogCollectorProperties properties) {
        this.properties = properties;
    }

    @Autowired(required = false)
    public void setInetUtils(InetUtils inetUtils) {
        TraceUtils.setInetUtils(inetUtils);
    }

    @Bean("traceExecutor")
    public SimpleAsyncTaskExecutor traceExecutor() {
        SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
        taskExecutor.setThreadNamePrefix("task-");
        taskExecutor.setTaskDecorator(TraceUtils::startTracer);
        return taskExecutor;
    }

    @Override
    protected void doFilterInternal(
            @NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain
    ) throws ServletException, IOException {
        try {
            String traceId = request.getHeader(TraceUtils.TRACE_HEADER);
            TraceUtils.startTracer(traceId, getIndexName());
            filterChain.doFilter(request, response);
        } finally {
            TraceUtils.clearTracer();
        }
    }

    @Nullable
    private String getIndexName() {
        return Optional.ofNullable(properties).map(XLogCollectorProperties::getIndexName).orElse(null);
    }
}
